﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharePointOptimizer.Model;
using SharePointOptimizer.BL.DataAnalysis;
using AG.Utilities;
namespace SharePointOptimizer.BL.DataAnalysis.IssueTypes
{
    public class DatabaseSizeCheck : IssueTypeCheckBase
    {

        public DatabaseSizeCheck(int issueTypeId)
            : base(issueTypeId)
        {

        }

        public override void Check()
        {
            try
            {
                SharePointOptimizerDataContext dc = new SharePointOptimizerDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;
                Farm farm = dc.Farms.FirstOrDefault();


                if (farm != null)
                {

                    Service service = farm.Services.SingleOrDefault(s => s.TypeName == "Microsoft SharePoint Foundation Web Application");


                    if (service != null)
                    {
                        var ServerQry = from cd in dc.Databases


                                        where (cd.DiskSizeRequired / (1024 * 1024) > issueType.ThresholdValue) && (cd.TypeName == "Content Database")

                                        select new { cd.DisplayName, cd.DiskSizeRequired, cd.DatabaseID };

                        foreach (var db in ServerQry)
                        {

                            //Get Issuetype object

                            //Get Issuetype object  And Create a new  Global issue object 

                            IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                            issue = new Issue();

                            issue.IssueType = issueType;
                            issue.TargetId = db.DatabaseID;
                            issue.Description = issueType.Description.Replace("{dbname}", db.DisplayName);
                            issue.Description = issue.Description.Replace("{dbsize}", (db.DiskSizeRequired / (1024 * 1024)).ToString());
                            issue.Description = issue.Description.Replace("{maxSize}", issueType.ThresholdValue.ToString());

                            dc.Issues.InsertOnSubmit(issue);
                        }

                        dc.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            
            
            
        }
       






    }

}